<template>
	<view class="tui-center">
		<uni-nav-bar fixed left-icon="back" title="填写订单"></uni-nav-bar>
		<view class="row-mg" style="padding: 0">
			<view class="tab-box x-f">
				<view class="tab-item x-c" :style="loginWay == 0 ? 'background: #fff':''" @tap="onLoginWay(0)">
					<text class="tab-title" :style="loginWay == 0 ? 'color:#6CB041': ''">店内自提</text>
					<view class="line-box" password v-show="loginWay === 0"></view>
				</view>
				<!--<view class="tab-item x-c" @tap="onLoginWay(1)" :style="loginWay == 1 ? 'background: #fff':''">
					<text class="tab-title" :style="loginWay == 1 ? 'color:#6CB041': ''">配送</text>
					<view class="line-box" v-show="loginWay === 1"></view>
				</view>-->
			</view>
			<view class="tab-chg" v-if="loginWay == 0">
				<view class="tui-flex bdr-bot" @tap="isShow = !isShow">
					<view class="tit">自提时间：</view>
					<view class="ipt">
						<input type="text" v-model="listFrom.pickTime"
							   disabled
							   class="uni-easyinput"
							   placeholder="选择时间">
					</view>
					<view>
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
				<view class="tui-flex">
					<view class="tit">预留手机号：</view>
					<view class="ipt">
						<input type="text" v-model="listFrom.phone" placeholder="请输入手机号" class="uni-easyinput">
					</view>
					<view>
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
			</view>
			<view class="tab-chg" v-else>
				<view class="tui-flex bdr-bot" @tap="navTo('/pages/perform/address?source=1')">
					<view class="address" v-if="addressList.length">
						<view>{{addressData.address}}</view>
						<view class="text">
							<text>{{addressData.contactName}}</text>
							<text class="tui-pd-left">{{addressData.contactPhone}}</text>
						</view>
					</view>
					<view class="address" v-else>
						请选择地址
					</view>
					<view style="width:8%;text-align: right;">
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
				<view class="tui-flex bdr-bot" @tap="isDisShow = !isDisShow">
					<view class="tit">配送时间：</view>
					<view class="ipt">
						<input type="text" v-model="listFrom.distributionTime"
							   disabled
							   class="uni-easyinput" placeholder="选择时间">
					</view>
					<view>
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<view class="row-mg">
			<view class="store-title">
				{{list.businName}}
			</view>
			<view style="border-bottom: 2rpx solid #eee;">
				<view class="tui-flex pad">
					<view class="img">
						<image :src="list.url" mode="aspectFill"></image>
					</view>
					<view class="row-conter">
						<view>{{list.title}}</view>
						<view>{{skuList.name}}</view>
						<view>数量：x{{listFrom.num}}</view>
					</view>
					<view>
						<view class="row-price">
							<text>￥{{skuList.discoutPrice ? skuList.discoutPrice : skuList.price}}</text>
						</view>
						<!--<number-box :value="listFrom.num"
						            :min="0"
						            :disabled="true"
						            :step="1"
						            @change="daysChange">
						</number-box>-->
					</view>
				</view>
				<view class="tui-flex pad">
					<view class="tit">买家留言：</view>
					<view class="ipt">
						<textarea @blur="bindTextAreaBlur" auto-height placeholder="买家留言" style="width: 100%;text-align: right"/>
					</view>
				</view>
				<view class="tui-flex pad" @tap="showModal = !showModal">
					<view class="tit">优惠券</view>
					<view class="ipt uni-easyinput">
						<text :style="{color:couponText != '暂无优惠券'?'#FF6666':'#999'}">{{couponText}}</text>
					</view>
					<view>
						<uni-icons type="arrowright" size="40" color="#999"></uni-icons>
					</view>
				</view>
				<view class="tui-flex pad">
					<view class="tit">
						余额(<text style="font-size: 28rpx;color: #FF6666">
						￥{{walletBalance}}
					</text>)
					</view>
					<view class="ipt uni-easyinput">
						<text style="color: #FF6666">-￥{{Balance}}</text>
					</view>
				</view>
			</view>
			<view class="tui-flex pad" style="justify-content: flex-end;">
				<view class="pefeta">
					<!--<text class="x-has">已优惠:
						<text>￥0</text>
					</text>-->
					<text>小计:
						<text class="subtotal">￥{{total}}</text>
					</text>
				</view>
			</view>
		</view>

		<time-alert title="自提时间"
		            rangeStartTime="8:00:00"
		            rangeEndTime="21:00:00"
		            subhead=''
		            rangeDay="2"
		            disabled="0,2"
		            :isShow="isShow"
		            :isNow="isNow"
		            @closeAlert="handelClose">
		</time-alert>
		<time-alert
				title="配送时间"
				subhead=""
				rangeStartTime="8:00:00"
				rangeEndTime="21:00:00"
				intervalTime="30"
				dayStartIntTime="20"
				rangeDay="5"
				disabled="0,2"
				:isShow="isDisShow"
				:isNow="isNow"
				:maskHide="maskHide"
				:rangeType="rangeType"
				@closeAlert="handelDisClose"
		></time-alert>
		<!--按钮-->
		<pay-btn :amount="total"
		         payText="提交订单"
		         title="总计"
		         @imPayment="imPayment(list)">
		</pay-btn>
		<coupon-modal :isShow="showModal"
		              :list="listData"
					  :businId="list.businId"
					  :money="totalNumMoney"
		              @closeAlert="handeClose"
		              @closeBtnClose="showModal = !showModal"
		></coupon-modal>

		<!-- 登录提示 -->
		<uni-login-model></uni-login-model>
	</view>
</template>
<script>
    import uniIcons from '@/components/uni-icons/uni-icons.vue'
    import payBtn from '@/components/payBtn/index'
    import timeAlert from '@/components/time-alert/time-alert.vue'
    import couponModal from '@/components/coolc-coupon/coupon-modal.vue'
    import numberBox from '@/components/uni-number-box/number-box.vue'
    import { mapState } from 'vuex'
    import uniLoginModel from '@/components/uni-login-model/uni-login-model.vue'

	export default {
		components: {
            uniIcons, payBtn, timeAlert, couponModal, numberBox, uniLoginModel
		},
		data() {
			return {
                loginWay: 0,
                list: {},
                isShow: false,
                isNow: true,
                isDisShow: false,
                maskHide: false,
                closeBtn: false,
                rangeType: true,
                showModal: false,
                listData: [],
                editFrom: {
                    cartProductDtoList: [
                        {
                            businId: 0,
                            orderId: '',
                            orderSpec: '',
                            ownSpec: '',
                            pics: '',
                            price: '',
                            productName: '',
                            productNo: '',
                            skuId: '',
                            title: ''
                        }
                    ],
                },
				listFrom: {
                    phone: '',
                    pickTime: '',
                    distributionTime: '',
                    num: 1,
                    buyerMessage: '',
				},
                addressData: {
                    contactName: undefined,
                    contactPhone: undefined,
                    userId: undefined,
                    address: undefined,
                    default: undefined,
                },
                listQuery: {
                    pageNum:1 ,
                    pageSize: 1
                },
                addressList: [],
                total: 0,
                id: undefined,
                skuList: {},
                totalNumMoney: 0,
                walletBalance: 0,
                Balance: 0,
                couponData: {},
                couponText: '暂无优惠券',
			}
		},
        computed: {
            ...mapState({
                userInfo: state => state.user.userInfo
            })
        },
        onLoad(option) {
            this.walletBalance = this.userInfo.walletBalance
            this.skuList = JSON.parse(option.data)
			this.listFrom.num = this.skuList.count
            this.id = option.id
            this.getList(option.id)
            this.loadData()
            this.getAddList()
		},
		methods: {
			//  获取地址
            getAddList() {
                this.$api.api('ship.list',this.listQuery).then(res => {
                    if (res.code == 200) {
                        this.addressList = res.data.list
                        if (this.addressList.length != 0) {
                            for (var item of this.addressList) {
                                this.addressData = item
                            }
                        }
                    } else {
                        this.$api.msg(res.message)
                    }
                })
            },
            imPayment(item) {
                let from = []
                if (this.loginWay == 0) {
                    if(!/(^1[3|4|5|7|8][0-9]{9}$)/.test(this.listFrom.phone)){
                        this.$api.msg('请输入正确的手机号码');
                        return;
                    }
                    from[0] = {
                        pickTime:this.listFrom.pickTime,
                        phone:this.listFrom.phone,
                        buyerMessage:this.listFrom.buyerMessage
                    }
                } else {
                    from[0] = {
                        ...this.addressData,
                        buyerMessage:this.listFrom.buyerMessage,
                        distributionTime:this.listFrom.distributionTime
                    }
                }
                this.editFrom.cartProductDtoList.forEach(i => {
                    this.$set(i,'title',this.skuList.name)
                    this.$set(i,'productName',this.skuList.name)
                    this.$set(i,'pics',this.skuList.img)
                    this.$set(i,'pic',this.skuList.img)
                    this.$set(i,'num',this.listFrom.num)
                    this.$set(i,'businId',item.businId)
                    this.$set(i, 'productNo',this.skuList.skuCode)
                    this.$set(i, 'price',this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price)
                    this.$set(i, 'skuId',this.skuList.skuId)
                    this.$set(i, 'stock',this.skuList.stock)
					this.$set(i, 'orderId',item.orderId)
                    return
                })
                this.editFrom = {
                    ...this.editFrom,
                    couponId: this.couponData.couponId,
                    shopId: this.list.businId,
                    balance: this.Balance,
                    productType:this.list.type,
                    totalAmount:this.totalNumMoney,
                    couponAmount: this.couponData.faceValue,
                    actAmount:this.total,
                    ownSpec:JSON.stringify(from),
                    // price: this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price
                }
                uni.showLoading()
                this.$api.api('order.create', this.editFrom).then(res => {
                    uni.hideLoading();
                    console.log(res)
                    if (res.code == 200) {
                        this.$wx.miniProgram.reLaunch({
                            url: `/pages/pay/pay?money=${this.total}&orderNo=${res.data.orderNo}&orderId=${this.list.spuId}&productType=1`,
                            success: function(res){
                                console.log(res)
                            },
                            fail: function(err){
                                console.log(err)
                            },
                        });
                    } else {
                        this.$api.msg(res.message)
                    }
                }).catch(error => {
                    this.$api.msg(error.message)
				})
            },
            //  商品信息
            getList(id) {
                uni.request({
                    url: `good/detail/${id}`,
                    method: 'GET',
                    header: {
                        'content-type': 'application/json',
                        'Authorization': 'Bearer ' + uni.getStorageSync('token')
                    },
                    success: (res) => {
                        if (res.data.code == 200) {
                            this.list = res.data.data
                            this.editFrom.num = this.skuList.count
                            this.total = this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price
                            this.totalNumMoney = this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price
                            if (this.list.pics) {
                                this.imgList = this.list.pics.split(',')
                            }
                            this.calcTotal()
                            let num = 0
                            if (this.walletBalance>=this.totalNumMoney) {
                                let balance  = this.walletBalance - (this.walletBalance - this.totalNumMoney)
                                this.Balance = Number(balance.toFixed(2))
                            } else {
                                num  = this.totalNumMoney - this.walletBalance
                                this.Balance = this.walletBalance
                            }
                            this.total = Number(num.toFixed(2))
                            if (this.total <=0) { this.total = 0}
						}
                    },
                    fail: (res) => {
                        uni.showToast({title: res.data.message, icon: 'none'})
                    }
                })
            },
            //	获取优惠券列表
            loadData() {
                uni.showLoading()
                this.$api.api('coupon.list', {status: 0}).then(res => {
                    uni.hideLoading();
                    if (res.code == 200 ){
                        this.listData = res.data
                        for (var i = 0, lenI = this.listData.length; i < lenI; ++i) {
                            this.listData[i].couponId = String(this.listData[i].couponId)
                        }
                        let list = [],matched;
						
						// 判断优惠券是否满足要求
						let flag = false;
						
						/* tanyi update 2021-12-10*/
						for (let i in res.data) {
							console.log("第", +i, "次，优惠券所属门店 = ", +res.data[i].bindShopIds, "当前门店," +this.list.businId)
							// 1. 优惠券所属门店 == 当前门店
							if (res.data[i].bindShopIds != this.list.businId) {
								console.log("门店不匹配")
								continue;
							}
							
							// 2. 优惠券金额 < 当前交易金额
							if (res.data[i].useConditionType == 'FULL_REDUCTION' && res.data[i].useConditionValue < this.totalNumMoney) {
								console.log("优惠券金额>当前订单金额")
								continue;
							}
							
							list.push(res.data[i])
							this.couponText = `有${list.length}张可用`
							this.listData = list
							flag = true;
							
							
						}
					
						if (!flag) {
							this.listData = [];
						}
						
						
						
                        /* res.data.forEach((item, index) => {
                            matched = item.bindShopIds.find((value)=>{return value == this.list.businId})
							console.log('matched'+matched)
                            if (item.useConditionType == 'NONE' || (item.useConditionType == 'FULL_REDUCTION' && item.useConditionValue < this.totalNumMoney && matched) || this.totalNumMoney < item.faceValue){
                                list.push(item)
                                this.couponText = `有${list.length}张可用`
                                this.listData = list
                            } else {
                                this.listData = []
                            }
                        }) */
                        /*function checkAdult(age) {
                            return this.list.businId;
                        }*/
                    } else {
                        uni.showToast({title: res.message, icon: 'none'})
                    }
                }).catch(error => {
                })
            },
            onLoginWay(flag) {
                this.loginWay = flag;
            },
            handelClose(data) {
                this.isShow = false;
                this.listFrom.pickTime = data._date
            },
            handelDisClose(data) {
                this.isDisShow = false
                this.listFrom.distributionTime = data._dateRange
            },
            navTo(url) {
                uni.navigateTo({ url: url })
            },
            handeClose(data) {
                this.showModal = false
                this.couponData = data
                if (data.faceValue == 0) {
                    this.couponText = data.name
                } else {
                    this.couponText = '-￥'+data.faceValue
                }
                let num = 0
                if (data.faceValue>=this.totalNumMoney) {
                    this.Balance = 0
                    let number1 = data.faceValue - this.totalNumMoney
                    this.total = Number(number1.toFixed(2))
                } else if (this.walletBalance>=this.totalNumMoney) {
                    let money  = this.walletBalance - (this.walletBalance - this.totalNumMoney) - data.faceValue
					console.log('money',money)
                    num = Number(money.toFixed(2))
                    this.Balance = num
                } else {
                    this.Balance = this.walletBalance
                    num  = this.totalNumMoney - this.Balance - data.faceValue
                    this.total = Number(num.toFixed(2))
                }
                if (this.total <= 0) { this.total = 0 }
            },
            daysChange(e) {
                this.listFrom.num = e
	            this.calcTotal()
            },
            calcTotal() {
                let total = 0;
                let price = this.skuList.discoutPrice ? this.skuList.discoutPrice : this.skuList.price
                total += price * this.listFrom.num
                this.totalNumMoney = Number(total.toFixed(2));
                this.total = Number(total.toFixed(2));
                /*if (this.couponData.faceValue) {
                    total = total - this.couponData.faceValue
                    this.Balance = Number(total.toFixed(2))
                    this.total = 0
                }*/
               /* if (this.walletBalance >= total) {
                    total = price * this.listFrom.num
                    this.Balance = Number(total.toFixed(2))
                    this.total = 0
                } else {
                    total = total - this.Balance
                    this.total = Number(total.toFixed(2));
				}
                if (this.total <= 0) { this.total = 0 }*/
            },
            bindTextAreaBlur: function (e) {
                this.listFrom.buyerMessage = e.detail.value
            }
		}
	}
</script>
<style lang="scss" scoped>
.row-mg {
	margin: 30rpx;
	background: #fff;
	border-radius: 15rpx;
	padding: 0 30rpx;
	.tab-box {
		display: flex;
		/*border-bottom: 2rpx solid #eee;*/
		.tab-item {
			flex: 1;
			height: 80rpx;
			position: relative;
			background: #6cb041bd;
			border-radius: 15rpx 0 0 0;
			transition: 0.3s;
			&:last-child {
				border-radius: 0 15rpx 0 0;
			}
			.tab-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #fff;
				margin-bottom: 10rpx;
			}
			.line-box {
				position: absolute;
				width: 120rpx;
				height: 4rpx;
				background: #6CB041;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
			}
		}
	}
	.store-title {
		padding: 15rpx 0;
		font-size: 32rpx;
		border-bottom: 2rpx solid #eee;
	}
	.pad {
		padding-top: 30rpx;
		&:last-child {
			padding-bottom: 30rpx;
		}
		.img {
			width: 25%;
			height: 160rpx;
			image{
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
			}
		}
		.row-conter {
			flex: 1;
			padding-left: 36rpx;
		}
		.row-price {
			font-weight: 600;
			text-align: center;
		}
	}
	.tab-chg {
		padding: 26rpx;
	}
	.tit {
		width: 32%;
		font-size: 32rpx;
	}
	.ipt {
		flex: 1;
	}
	.uni-easyinput {
		text-align: right;
	}
	.pefeta {
		.x-has {
			padding-right: 30rpx;
			text {
				color: red;
				font-size: 34rpx;
				padding-left: 10rpx;
			}
		}
		.subtotal {
			font-size: 36rpx;
			font-weight: 600;
			padding-left: 10rpx;
			color: #ff6666;
		}
	}
	.address {
		font-size: 34rpx;
		flex: 1;
		padding-right: 10rpx;
		.text {
			font-size: 28rpx;
			color: #999;
		}
	}
	.bdr-bot {
		padding-bottom: 15rpx;
	}
}
</style>